package com.lei.springbootpractice.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lei.springbootpractice.dao.CartDao;
import com.lei.springbootpractice.dao.ProductBunchDao;
import com.lei.springbootpractice.pojo.CartPojo;
import com.lei.springbootpractice.pojo.ProductBunchPojo;
import com.lei.springbootpractice.pojo.ProductsPojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CartService {
    @Autowired
    CartDao cartDao;

    @Autowired
    ProductBunchDao productBunchDao;

    @Autowired
    ProductsService productsService;

    public List<CartPojo> getCartByUserId(String userId) {
        List<CartPojo> carts = cartDao.selectList(new QueryWrapper<CartPojo>().eq("user_id", userId));
        for (CartPojo cart : carts) {
            List<ProductBunchPojo> productBunches = productBunchDao.selectList(
                new QueryWrapper<ProductBunchPojo>()
                    .eq("cart_id", cart.getCartId())
                    .eq("status", "IN_CART"));
            for (ProductBunchPojo bunch : productBunches) {
                ProductsPojo product = productsService.getProductById(bunch.getProductId());
                bunch.setProduct(product);
            }
            cart.setProductBunches(productBunches);
        }
        return carts;
    }

    private CartPojo getOrCreateUserCart(String userId) {
        List<CartPojo> carts = cartDao.selectList(new QueryWrapper<CartPojo>().eq("user_id", userId));
        if (!carts.isEmpty()) {
            return carts.get(0);
        }

        CartPojo newCart = new CartPojo();
        newCart.setUserId(userId);
        newCart.setQuantity(0);
        if (cartDao.insert(newCart) <= 0) {
            throw new RuntimeException("创建购物车失败");
        }
        return newCart;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean addToCart(CartPojo cartItem) {
        ProductsPojo product = productsService.getProductById(cartItem.getProductId());
        /*
        if (product == null) {
            throw new RuntimeException("商品不存在");
        }
        */


        if (cartItem.getQuantity() > product.getRest()) {
            throw new RuntimeException("库存不足，当前库存: " + product.getRest());
        }

        CartPojo userCart = getOrCreateUserCart(cartItem.getUserId());

        ProductBunchPojo newBunch = new ProductBunchPojo();
        newBunch.setCartId(userCart.getCartId());
        newBunch.setProductId(cartItem.getProductId());
        newBunch.setQuantity(cartItem.getQuantity());
        newBunch.setTolPrice(product.getPrice() * cartItem.getQuantity());

        return productBunchDao.insert(newBunch) > 0;
    }

    @Transactional
    public boolean removeFromCart(String cartId) {
        return cartDao.deleteById(cartId) > 0;
    }

    @Transactional
    public boolean clearCart(String userId) {
        return cartDao.delete(new QueryWrapper<CartPojo>().eq("user_id", userId)) > 0;
    }

    @Transactional
    public boolean deleteCartByUserId(String userId) {
        return cartDao.delete(new QueryWrapper<CartPojo>().eq("user_id", userId)) > 0;
    }

    @Transactional
    public boolean removeProductBunch(String bunchId) {
        return productBunchDao.deleteById(bunchId) > 0;
    }

    @Transactional
    public boolean updateProductBunchQuantity(String bunchId, int quantity) {
        ProductBunchPojo bunch = productBunchDao.selectById(bunchId);
        if (bunch == null) {
            return false;
        }

        // 加载商品信息
        ProductsPojo product = productsService.getProductById(bunch.getProductId());
        if (product == null) {
            throw new RuntimeException("商品不存在");
        }

        bunch.setQuantity(quantity);
        bunch.setTolPrice(product.getPrice() * quantity);
        bunch.setProduct(product); // 确保product对象不为null

        return productBunchDao.updateById(bunch) > 0;
    }
}
